import React, { useState } from "react";
import { Form, Input, Button, NavBar, TextArea, DatePicker } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import axios from "axios";

const ConsultationNew = () => {
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm(); // Use Form.useForm() instead of useState

  const onFinish = async (values) => {
    try {
      // 调用会诊的接口
      const response = await axios.post(
        "http://localhost:3000/huan/Huiadd",
        values
      );
      if (response.data.code === 200) {
        alert(response.data.msg);
        // 跳转会诊主界面
        navigate("/layout/consultation");
      }
    } catch (error) {
      console.error("提交失败:", error);
      alert(error.message);
    }
  };

  return (
    <div className="consultation-new">
    <NavBar onBack={() => navigate(-1)}>新建会诊</NavBar>
    <Form 
      form={form} 
      onFinish={onFinish} 
      layout="vertical"
      className="consultation-form"
    >
        <Form.Item
          name="patientName"
          label="患者姓名"
          rules={[{ required: true, message: "请输入患者姓名" }]}
        >
          <Input placeholder="请输入患者姓名" />
        </Form.Item>

        <Form.Item
          name="age"
          label="年龄"
          rules={[{ required: true, message: "请输入年龄" }]}
        >
          <Input type="number" placeholder="请输入年龄" />
        </Form.Item>

        <Form.Item
          name="department"
          label="科室"
          rules={[{ required: true, message: "请选择科室" }]}
        >
          <Input placeholder="请选择科室" />
        </Form.Item>

        <Form.Item
          name="desc"
          label="病情描述"
          rules={[{ required: true, message: "请详细描述患者病情" }]}
        >
          <TextArea placeholder="请详细描述患者病情" rows={4} />
        </Form.Item>

        <Form.Item
          name="expectedTime"
          label="期望会诊时间"
          rules={[{ required: true, message: "请选择期望会诊时间" }]}
          trigger="onConfirm"
          onClick={() => {
            setVisible(true);
          }}
        >
          <DatePicker
            visible={visible}
            onClose={() => {
              setVisible(false);
            }}
            precision="day"
            min={new Date()}
          >
            {(value) => (value ? value.toLocaleDateString() : "请选择日期")}
          </DatePicker>
        </Form.Item>

        
        <Button
          block
          color="primary"
          onClick={() => form.submit()}
        >
          提交申请
        </Button>
      </Form>
    </div>
  );
};

export default ConsultationNew;
